<?php

namespace App\SubApps\Account\Controllers;

use App\SubApps\Account\Entities\OauthAppsEntity;
use App\SubApps\Account\Models\OauthAppsLoginLogModel;
use Hilaoyu\LaravelExtend\ControllerBaseResource;
use Hilaoyu\Utils\UtilHtml;
use Hilaoyu\Utils\UtilHttp;
use Hilaoyu\Utils\UtilSupport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class OauthAppsController extends ControllerBaseResource
{

    protected function entity()
    {
        return new OauthAppsEntity();
    }

     protected function alterModelsQuery($query,Request $request)
    {
        $query = parent::alterModelsQuery($query,$request);

        $search = [
            'keyword' => $request->input('keyword',''),
            'status' => $request->input('status',''),
        ];

        if($search['status'] != ''){
            $query = $query->where('status','=',$search['status']);

        }
        if(!empty($search['keyword'])){
            $query = $query->where(function ($query) use ($search){
                $query->orWhere('domain','like','%'. $search['keyword'] .'%')
                    ->orWhere('name','like','%'. $search['keyword'] .'%');
            });
        }



        comResponse()->with( $search,'search')
            ->with( UtilHtml::statusOptions($search['status'],'是否启用'),'status_options');
            ;
        return $query;
    }

     protected function alterModelsLoaded($models, Request $request)
     {
         $models = parent::alterModelsLoaded($models, $request);
         $models->map(function ($item) {
             $item->setAttribute('edit_link', route('web.console.oauth-apps.view', ['id' => $item->id]));
             return $item;
         });

         return $models;
     }

     protected function alterModelLoaded($model, Request $request)
     {
         $model = parent::alterModelLoaded($model, $request);

         comResponse()
             ->with(UtilHtml::statusOptions($model->status), 'status_options');
         return $model;
     }
    protected function alterModelSaveData(Request $request,$id='')
    {
        $data = [
            'domain' => $request->input('domain',''),
            'name' => $request->input('name',''),
            'secret' => $request->input('secret',''),
            'return_url' => $request->input('return_url',[]),
            'logo' => $request->input('logo',''),
            'status' => $request->input('status','0'),
            'summary' => $request->input('summary',''),
        ];


        return $data;
    }




    public function redirectBack(Request $request){

        if($oauth_app_id = $request->route('id','')){
            $oauth_app = $this->entity()->findById($oauth_app_id);
            if(!$oauth_app){
                return comResponse()->failed('应用ID错误')->back();
            }
            $oauth_data = [
                'app' => $oauth_app,
                'back_url' => data_get(collect($oauth_app->return_url)->first(),'url',''),
                'state' => '',
            ];
        }else{
            $oauth_data = UtilSupport::tryQuiet(function () {
                return session('oauth_data');
            });
        }

        $back_url = $request->input('back_url',data_get($oauth_data,'back_url',''));


        $state = $request->input('state',data_get($oauth_data,'state',''));
        if(!$back_url){
            return comResponse()->failed('回调地址错误')->back();
        }

        $token_id = Auth::user()->getAuthenticatedToken('id');
        $redirect_url = UtilHttp::buildUrl($back_url,[
            'code' =>  $token_id,
            'state' =>  $state,
        ]);


        UtilSupport::tryQuiet(function () use ($oauth_data,$token_id,$back_url,$state) {
            session()->forget('oauth_data');
            if(data_get($oauth_data,'app.id','')){
                (new OauthAppsLoginLogModel())->fill([
                    'token_id' => $token_id,
                    'user_id' => data_get(Auth::user(),'id','') ,
                    'user_model'  => get_class(Auth::user()),
                    'login_platform'  => request()->getClientPlatform(),
                    'login_source'  => request()->getClientSource(),
                    'login_ip'  => request()->ip(),
                    'referer'  => request()->header('referer'),
                    'oauth_app_id'  => data_get($oauth_data,'app.id','') ,
                    'oauth_app_return'  => $back_url ,
                    'oauth_app_state'  => $state ,
                ])->save();

            }
        });

        //dd($redirect_url);
        return comResponse()->success('登录成功，正在跳转。。。')->redirect($redirect_url);
    }



}
